package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import com.bwie.vo.ToKenVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author 36167
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-03-08 10:06:46
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

     @Value("${jwt.key}")
     private String key;

     @Autowired
     private RabbitTemplate rabbitTemplate;





     @Autowired
     private StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {

        List<User> users = userMapper.selectList(null);
        String key1="xty:";
        for (User user : users) {
            stringRedisTemplate.opsForZSet().incrementScore(key1,user.getUsername(),user.getId());
        }

        if(StringUtils.isEmpty(loginInfoVo.getUserName())){
            return R.ERROR(500,"账号不允许为空");
        }else if (StringUtils.isEmpty(loginInfoVo.getUserPass())){
            return R.ERROR(500,"密码不能为空");
        }


        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,loginInfoVo.getUserName());
        wrapper.eq(User::getPassword,loginInfoVo.getUserPass());
        User one = getOne(wrapper);
        if (one==null){
            throw new RuntimeException("用户不存在");
        }

        //长期token
        String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, key).claim("uid", one.getId()).compact();
        //短期token
        String redistoken = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7200 * 1000))
                .signWith(SignatureAlgorithm.HS256, key).
                claim("uid", one.getId()).compact();
        stringRedisTemplate.opsForValue().set(redistoken,token);
        ToKenVo toKenVo = new ToKenVo();
        toKenVo.setRedistokentime(System.currentTimeMillis()+7200*1000);
        toKenVo.setRedistoken(redistoken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",toKenVo);
        map.put("user",one);
        return R.OK(map);
    }

    @Override
    public R refTokne(String token) {
        Boolean b = stringRedisTemplate.hasKey(token);

        String s = stringRedisTemplate.opsForValue().get(token);
        log.info("是否存在:{},值为:{}",b,s);
        if (s==null){
       throw new RuntimeException("token过期");
        }
        Claims body = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody();
        Integer uid = body.get("uid", Integer.class);
        String redistoken = Jwts.builder().
                setExpiration(new Date(System.currentTimeMillis() + 7200 * 1000)).
                signWith(SignatureAlgorithm.HS256, key).claim("uid", uid).compact();
        stringRedisTemplate.delete(token);
        stringRedisTemplate.opsForValue().set(redistoken,s);


        ToKenVo toKenVo = new ToKenVo();
        toKenVo.setRedistoken(redistoken);
        toKenVo.setRedistokentime(System.currentTimeMillis()+7200+1000);
        return R.OK(toKenVo);
    }

    @Override
    public R list1() {
        return R.OK( userMapper.selectList(null));
    }
}




